# -*- coding: utf-8 -*-
"""
Created on Fri Aug 09 16:45:15 2013

@author: Jeanhwea
"""

import os
from ftplib import FTP

rootpath = '../outputfile/'

# ASCII files download
if os.path.exists('README.out'):
    raise IOError('refusing to overwrite your README file')
def writeline(data):
    fd.write(data)
    fd.write(os.linesep)
f = FTP('ftp.kernel.org')
f.login()
f.cwd('/pub/linux/kernel')
fd = open(rootpath+'README.out', 'w')
f.retrlines('RETR README', writeline)
fd.close()
f.quit()

# Binary files download
if os.path.exists('patch8.gz'):
    raise IOError('refusing to overwrite your patch8.gz file')
f = FTP('ftp.kernel.org')
f.login()
f.cwd('/pub/linux/kernel/v1.0')
fd = open(rootpath+'patch8.gz', 'wb')
f.retrbinary('RETR patch8.gz', fd.write)
fd.close()
f.quit()

# Get s bare directory listing
f = FTP('ftp.ibiblio.org')
f.login()
f.cwd('/pub/academic/astronomy/')
entries = f.nlst()
entries.sort()
print len(entries), "entries:"
for entry in entries:
    print entry
f.quit()

# Recurse into directory
from ftplib import FTP, error_perm
import os
def walk_dir(f, dirpath):
    original_dir = f.pwd()
    try:
        f.cwd(dirpath)
    except error_perm:
        return # ignore non-directories and ones we cannot enter
    print dirpath
    names = f.nlst()
    for name in names:
        walk_dir(f, dirpath + '/' + name)
    f.cwd(original_dir) # return to cwd of our caller
f = FTP('ftp.kernel.org')
f.login()
walk_dir(f, '/pub/linux/kernel/Historic/old-versions')
f.quit()

# Delete and creat things is easy